<template>
  <a-card style="box-sizing: border-box; padding: 30px">
    <!-- 选择下单的应用列表 -->
    <a-form>
      <div style="display: flex; flex-direction: row">
        <!-- <p style="margin-top:9px;margin-right:10px;"></p> -->
        <a-form-item label="" class="table-head-layout">
          <a-select v-model:value="appId" @change="changeAppId" style="width: 300px">
            <a-select-option v-for="item in mchAppList" :key="item.id">{{ item.appName }} [{{ item.id }}]</a-select-option>
          </a-select>
        </a-form-item>
      </div>
    </a-form>

    <!-- 未配置支付方式提示框 -->
    <a-divider v-if="!appId">请选择应用APPID</a-divider>
    <a-divider v-else-if="noConfigText">您尚未配置任何支付方式</a-divider>
    <a-divider v-else />

    <!-- 支付测试面板 v-if=""-->
    <div style="width: 100%" class="paydemo" v-if="payTestShow()">
      <div class="paydemo-type-content">
        <div class="paydemo-type-name article-title" v-show="showTitle('WX')">微信支付</div>
        <div class="paydemo-type-body">
          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('WX_NATIVE') >= 0"
            @click="changeCurrentWayCode('WX_NATIVE', 'codeUrl')"
            :class="{ this: currentWayCode === 'WX_NATIVE' }"
          >
            <img src="/src/assets/svg/payTest/wx_native.svg" class="paydemo-type-img" />
            <span class="color-change">微信二维码</span>
          </div>

          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('WX_BAR') >= 0"
            @click="changeCurrentWayCode('WX_BAR', '')"
            :class="{ this: currentWayCode === 'WX_BAR' }"
          >
            <img src="/src/assets/svg/payTest/wx_bar.svg" class="paydemo-type-img" /><span class="color-change">微信条码</span>
          </div>

          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('WX_JSAPI') >= 0"
            @click="changeCurrentWayCode('WX_JSAPI', 'codeUrl')"
            :class="{ this: currentWayCode === 'WX_JSAPI' }"
          >
            <img src="/src/assets/svg/payTest/wx_jsapi.svg" class="paydemo-type-img" /><span class="color-change">公众号/小程序</span>
          </div>

          <div
            class="paydemo-type-h5"
            v-show="appPaywayList.indexOf('WX_H5') >= 0"
            @click="changeCurrentWayCode('WX_H5', 'payurl')"
            :class="{ this: currentWayCode === 'WX_H5' }"
          >
            <img src="/src/assets/svg/payTest/wx_h5.svg" class="paydemo-type-img" /><span class="color-change">微信H5</span>
          </div>
        </div>

        <div class="paydemo-type-name article-title" v-show="showTitle('ALI')">支付宝支付</div>
        <div class="paydemo-type-body">
          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('ALI_QR') >= 0"
            @click="changeCurrentWayCode('ALI_QR', 'codeUrl')"
            :class="{ this: currentWayCode === 'ALI_QR' }"
          >
            <img src="/src/assets/svg/payTest/ali_qr.svg" class="paydemo-type-img" /><span class="color-change">支付宝二维码</span>
          </div>

          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('ALI_BAR') >= 0"
            @click="changeCurrentWayCode('ALI_BAR', '')"
            :class="{ this: currentWayCode === 'ALI_BAR' }"
          >
            <img src="/src/assets/svg/payTest/ali_bar.svg" class="paydemo-type-img" /><span class="color-change">支付宝条码</span>
          </div>

          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('ALI_JSAPI') >= 0"
            @click="changeCurrentWayCode('ALI_JSAPI', 'codeUrl')"
            :class="{ this: currentWayCode === 'ALI_JSAPI' }"
          >
            <img src="/src/assets/svg/payTest/ali_jsapi.svg" class="paydemo-type-img" /><span class="color-change">支付宝生活号</span>
          </div>

          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('ALI_PC') >= 0"
            @click="changeCurrentWayCode('ALI_PC', 'payurl')"
            :class="{ this: currentWayCode === 'ALI_PC' }"
          >
            <img src="/src/assets/svg/payTest/ali_pc.svg" class="paydemo-type-img" /><span class="color-change">支付宝PC网站</span>
          </div>

          <div>
            <div
              class="paydemo-type-h5"
              v-show="appPaywayList.indexOf('ALI_WAP') >= 0"
              @click="changeCurrentWayCode('ALI_WAP', 'payurl')"
              :class="{ this: currentWayCode === 'ALI_WAP' }"
            >
              <img src="/src/assets/svg/payTest/ali_wap.svg" class="paydemo-type-img" /><span class="color-change">支付宝WAP</span>
            </div>
          </div>
        </div>

        <div class="paydemo-type-name article-title" v-show="showQtTitle()">其它支付</div>
        <div class="paydemo-type-body">
          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('WX_JSAPI') >= 0 || appPaywayList.indexOf('ALI_JSAPI') >= 0"
            @click="changeCurrentWayCode('QR_CASHIER', 'codeImgUrl')"
            :class="{ this: currentWayCode === 'QR_CASHIER' }"
          >
            <img src="/src/assets/svg/payTest/qr_cashier.svg" class="paydemo-type-img" /><span class="color-change">聚合主扫</span>
          </div>

          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('WX_BAR') >= 0 || appPaywayList.indexOf('ALI_BAR') >= 0"
            @click="changeCurrentWayCode('AUTO_BAR', 'codeUrl')"
            :class="{ this: currentWayCode === 'AUTO_BAR' }"
          >
            <img src="/src/assets/svg/payTest/auto_bar.svg" class="paydemo-type-img" /><span class="color-change">聚合被扫</span>
          </div>

          <div
            class="paydemo-type color-change"
            v-show="appPaywayList.indexOf('PP_PC') >= 0"
            @click="changeCurrentWayCode('PP_PC', 'payurl')"
            :class="{ this: currentWayCode === 'PP_PC' }"
          >
            <img src="/src/assets/svg/payTest/pp_pc.svg" class="paydemo-type-img" /><span class="color-change">PayPal支付</span>
          </div>
        </div>
      </div>

      <a-divider />
      <!-- 订单信息 -->
      <div class="paydemo-type-content">
        <div class="paydemo-type-name article-title">支付信息</div>
        <form class="layui-form">
          <div class="paydemo-form-item">
            <label>订单编号：</label><span id="payMchOrderNo">{{ mchOrderNo }}</span>
            <span @click="randomOrderNo" class="paydemo-btn" style="padding: 0 3px">刷新订单号</span>
          </div>
          <div class="paydemo-form-item">
            <label>订单标题：</label>
            <a-input v-model:value="goodsSubject" style="width: 200px" />
          </div>

          <div class="paydemo-form-item">
            <label>分账方式：</label>
            <a-radio-group v-model:value="divisionMode" style="display: flex">
              <div style="display: flex">
                <a-radio :value="0">订单不分账</a-radio>
                <a-radio :value="1">支付完成自动分账</a-radio>
                <a-radio :value="2">手动分账（冻结商户资金， 只能通过API发起分账后解冻）</a-radio>
              </div>
            </a-radio-group>
          </div>

          <a-divider />

          <div class="paydemo-form-item">
            <span>支付金额(元)：</span>
            <a-radio-group name="radioGroup" default-value="0.01" style="display: flex" v-model:value="paytestAmount">
              <div @click="amountInput = false" style="display: flex">
                <a-radio value="0.01" @click="paytestAmount = '0.01'">￥0.01</a-radio>
                <a-radio value="0.15" @click="paytestAmount = '0.15'">￥0.15</a-radio>
                <a-radio value="0.21" @click="paytestAmount = '0.21'">￥0.21</a-radio>
                <a-radio value="0.29" @click="paytestAmount = '0.29'">￥0.29</a-radio>
                <a-radio value="0.64" @click="paytestAmount = '0.64'">￥0.64</a-radio>
              </div>
              <a-radio @click="amountInputShow">
                <span style="margin-right: 3px">自定义金额</span>
                <a-input-number ref="amountInputFocus" :max="100000" :min="0.01" v-show="amountInput" v-model="paytestAmount" :precision="2" />
              </a-radio>
            </a-radio-group>
          </div>

          <div style="margin-top: 20px; text-align: left">
            <!-- <span style="color: #FD482C;font-size: 18px;padding-right: 10px;" id="amountShow">{{ paytestAmount }}</span> -->
            <a-button @click="immediatelyPay" style="padding: 5px 20px; background-color: #1953ff; border-radius: 5px; color: #fff"
              >立即支付</a-button
            >
          </div>
        </form>
      </div>
    </div>
  </a-card>

  <!-- <pay-test-modal ref="payTestModal" @closeBarCode="$refs.payTestBarCode.visible = false" ></pay-test-modal> -->

  <!-- 条码弹框 -->
  <!-- <pay-test-bar-code ref="payTestBarCode" @barCodeValue="barCodeChange" @CodeAgainChange="testCodeChange"></pay-test-bar-code> -->

  <!-- 二维码弹窗 -->
  <QrCodeModel @register="registerModal" :showFooter="false" />
</template>

<script lang="ts" name="pay-test" setup>
  import { useModal } from "/@/components/Modal"
  import { unifiedOrder } from "./pay.api"
  import { listPayPassage, listAllMchApp } from "/@/api/pay"
  // import PayTestModal from './PayTestModal' // 二维码对话框组件
  // import PayTestBarCode from './PayTestBarCode' // 条码对话框组件
  import QrCodeModel from "./QrCodeModel.vue"
  import { ref, onUnmounted, onMounted } from "vue"
  import { useRouter } from "vue-router"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  const router = useRouter()
  const [registerModal, { openModal, closeModal }] = useModal()

  // app列表
  const mchAppList = ref<any>([])
  // 已选择的appId
  const appId = ref("")
  const mchNo = ref("")
  // 商户app支持的支付方式
  const appPaywayList = ref<any>([])
  // 以何种方式进行支付，默认是微信二维码
  const currentWayCode = ref("")
  // 支付参数
  const currentPayDataType = ref("")
  // 模拟商户订单号
  const mchOrderNo = ref("")
  // 条码的值
  const authCode = ref("")
  // 支付金额，默认为0.01
  const paytestAmount = ref("0.01")
  // 自定金额输入框是否展示
  const amountInput = ref(false)
  // 尚无任何配置分割线提示文字
  const noConfigText = ref(false)
  // 订单分账模式
  const divisionMode = ref("0")
  // 订单标题
  const goodsSubject = ref("接口调试")

  onMounted(async () => {
    // 获取传入的参数，如果参数存在，则为appId 重新赋值
    const getAppId = router.currentRoute.value.params.appId as string
    if (getAppId) {
      appId.value = getAppId // appId赋值
      appPaywayListHandle(getAppId) // 调用appPaywayListHandle，展示支付方式
    }

    // 请求接口，获取所有的appid，只有此处进行pageSize=-1传参
    const data = await listAllMchApp({})
    console.log("listAllMchApp", data)

    mchAppList.value = data
    if (mchAppList.value.length > 0) {
      // 赋予默认值
      appId.value = mchAppList.value[0].id
      mchNo.value = mchAppList.value[0].mchNo
      // 根据appId的值，动态显示支付方式
      appPaywayListHandle(appId.value)
    }

    // 在进入页面时刷新订单号
    randomOrderNo()
  })

  // 根据不同的appId展示不同的支付方式(在下拉框切换时和在携带参数进入页面时调用)
  const appPaywayListHandle = async (value) => {
    if (!value) {
      appPaywayList.value = []
      return false
    }
    appId.value = value
    mchNo.value = mchAppList.value.filter((e) => e.id === value)[0].mchNo
    // value
    const data = await listPayPassage({ appId: value, status: "1" })
    appPaywayList.value = data.map((obj) => {
      return obj.wayCode
    })
    if (appPaywayList.value.length === 0) {
      noConfigText.value = true
    } else {
      noConfigText.value = false
    }
  }

  // 支付板块是否展示
  const payTestShow = () => {
    // 如果未选择appid，或者支付方式列表为0，则不显示支付体验板块
    if (appId.value === "" || appPaywayList.value.length === 0) {
      return false
    } else {
      return true
    }
  }

  const changeCurrentWayCode = (wayCode, payDataType) => {
    // 切换支付方式
    console.log("currentPayDataType wayCode", payDataType, wayCode)

    currentWayCode.value = wayCode
    currentPayDataType.value = payDataType
  }

  // 变更 appId的事件
  const changeAppId = (value) => {
    appPaywayListHandle(value) // 根据appId的值，动态显示支付方式
  }

  // 刷新订单号
  const randomOrderNo = () => {
    mchOrderNo.value = "M" + new Date().getTime() + Math.floor(Math.random() * (9999 - 1000) + 1000)
  }

  // 获取条码的值
  const barCodeChange = (value) => {
    authCode.value = value
    immediatelyPay()
  }

  // 立即支付按钮
  const immediatelyPay = () => {
    // 判断支付金额是否为0
    if (!paytestAmount.value || paytestAmount.value == "0.00") {
      return createMessage.error("请输入支付金额")
    }

    // 判断是否选择支付方式
    if (currentWayCode.value === "") {
      return createMessage.error("请选择支付方式")
    }

    // 请输入订单标题
    if (!goodsSubject.value || goodsSubject.value.length > 20) {
      return createMessage.error("请输入正确的订单标题[20字以内]")
    }

    // 判断是否为条码支付
    // if (!this.$refs.payTestBarCode.getVisible() && (this.currentWayCode === 'WX_BAR' || this.currentWayCode === 'ALI_BAR' || this.currentWayCode === 'AUTO_BAR')) {
    //     this.$refs.payTestBarCode.showModal()
    //     return
    // }

    unifiedOrder({
      appId: appId.value,
      mchNo: mchNo.value,
      // jsapi 默认使用聚合二维码支付
      wayCode: currentWayCode.value === "WX_JSAPI" || currentWayCode.value === "ALI_JSAPI" ? "QR_CASHIER" : currentWayCode.value, // 支付方式
      amount: paytestAmount.value, // 支付金额
      mchOrderNo: mchOrderNo.value, // 订单编号

      authCode: authCode.value,
      divisionMode: divisionMode.value,
      channelExtra: {
        payDataType: currentPayDataType.value, // 支付参数（二维码，条码）
      },
      version: "1.0",
      sign: "1",
      reqTime: "1",
      signType: "1",
      currency: "CNY",
      goodsSubject: goodsSubject.value,
      goodsBody: "测试",
    })
      .then((res) => {
        openModal(true, { wayCode: currentWayCode.value, apiRes: res })
        randomOrderNo() // 刷新订单号
      })
      .catch(() => {
        createMessage.error(`支付异常`)
        closeModal()
        randomOrderNo() // 刷新订单号
      })
  }

  // 此处判断，微信，支付宝，聚合码，哪种支付方式一个都没配置，如果未配置，则不显示该板块，若等于-1 则表示不存在
  const showTitle = (parameterA) => {
    // if (this.appPaywayList.toString().indexOf(parameterA) === -1) {
    //   return false
    // } else {
    //   return true
    // }
    return true
  }
  // 聚合支付标题显示
  const showQtTitle = () => {
    if (
      appPaywayList.value.toString().indexOf("WX") !== -1 ||
      appPaywayList.value.toString().indexOf("ALI") !== -1 ||
      appPaywayList.value.toString().indexOf("PP_PC") !== -1
    ) {
      return true
    } else {
      return false
    }
  }

  // 自定义金额输入框是否展示
  const amountInputShow = () => {
    amountInput.value = true
    paytestAmount.value = ""
  }

  // 条码弹窗点击x或者蒙版关闭
  const testCodeChange = () => {
    randomOrderNo() // 刷新订单号
  }
</script>

<style scoped lang="css">
  @import "./payTest.css";
</style>
